// 游戏主要变量
let canvas, ctx;
let gameRunning = false;
let score = 0;
let level = 1;
let timeLeft = 60;
let fruits = [];
let paddle;
let lastTime = 0;
let fruitGenerationInterval = 1500; // 初始水果生成间隔(毫秒)
let lastFruitGenerationTime = 0;
let backgroundMusic, hitSound, missSound;
let soundEnabled = true;
let musicEnabled = true;
let particles = [];
let timerInterval;

// DOM元素
const mainMenu = document.getElementById('main-menu');
const gameArea = document.getElementById('game-area');
const settingsMenu = document.getElementById('settings-menu');
const leaderboardMenu = document.getElementById('leaderboard-menu');
const startButton = document.getElementById('start-button');
const settingsButton = document.getElementById('settings-button');
const leaderboardButton = document.getElementById('leaderboard-button');
const restartButton = document.getElementById('restart-button');
const backToMenuButton = document.getElementById('back-to-menu');
const backToMainMenuButton = document.getElementById('back-to-main-menu');
const scoreElement = document.getElementById('score');
const levelElement = document.getElementById('level');
const timerElement = document.getElementById('timer');
const finalScoreElement = document.getElementById('final-score');
const highScoreElement = document.getElementById('high-score');
const gameOverScreen = document.getElementById('game-over');
const backgroundMusicElement = document.getElementById('background-music');
const hitSoundElement = document.getElementById('hit-sound');
const missSoundElement = document.getElementById('miss-sound');

// 水果类
class Fruit {
    constructor(x, y, radius, speedX, speedY, color, points, type = 'normal', name = '水果') {
        this.x = x;
        this.y = y;
        this.radius = radius;
        this.speedX = speedX;
        this.speedY = speedY;
        this.color = color;
        this.points = points;
        this.type = type; // 'normal', 'special', 'bomb'
        this.name = name;
        this.active = true;
        this.image = new Image();
        this.image.src = `https://cdn-icons-png.flaticon.com/512/135/135667.png`; // 默认水果图片
    }

    update() {
        this.x += this.speedX;
        this.y += this.speedY;

        // 检查是否碰到左右边界
        if (this.x - this.radius < 0 || this.x + this.radius > canvas.width) {
            this.speedX = -this.speedX;
        }
    }

    draw() {
        ctx.save();
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        ctx.fillStyle = this.color;
        ctx.fill();
        
        // 添加发光效果
        ctx.shadowBlur = 15;
        ctx.shadowColor = this.color;
        ctx.stroke();
        ctx.shadowBlur = 0;
        
        // 绘制水果名称
        ctx.font = '10px Arial';
        ctx.fillStyle = 'white';
        ctx.textAlign = 'center';
        ctx.fillText(this.name, this.x, this.y + 3);
        
        ctx.restore();
    }

    checkCollision(paddle) {
        // 检查水果是否与接球板碰撞
        const paddleTop = paddle.y;
        const paddleBottom = paddle.y + paddle.height;
        const paddleLeft = paddle.x;
        const paddleRight = paddle.x + paddle.width;

        if (this.y + this.radius > paddleTop && 
            this.y - this.radius < paddleBottom && 
            this.x + this.radius > paddleLeft && 
            this.x - this.radius < paddleRight) {
            
            // 计算碰撞点相对于接球板中心的位置
            const hitPosition = (this.x - (paddleLeft + paddle.width / 2)) / (paddle.width / 2);
            
            // 根据碰撞位置调整水果的水平速度
            this.speedX = hitPosition * 5; // 调整这个值可以改变反弹角度
            
            // 反转垂直速度
            this.speedY = -Math.abs(this.speedY);
            
            // 根据水果类型处理碰撞效果
            if (this.type === 'bomb') {
                // 炸弹水果爆炸，结束游戏
                return 'bomb';
            } else if (this.type === 'special') {
                // 特殊水果增加更多分数
                return 'special';
            }
            
            // 普通水果正常接住
            return 'normal';
        }
        
        return null;
    }
}

// 接球板类
class Paddle {
    constructor(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    draw() {
        ctx.beginPath();
        ctx.rect(this.x, this.y, this.width, this.height);
        ctx.fillStyle = '#00e5ff';
        ctx.fill();
        
        // 添加发光效果
        ctx.shadowBlur = 15;
        ctx.shadowColor = '#00e5ff';
        ctx.stroke();
        ctx.shadowBlur = 0;
    }

    update(mouseX) {
        // 更新接球板位置
        this.x = mouseX - this.width / 2;
        
        // 确保接球板不会超出画布边界
        if (this.x < 0) this.x = 0;
        if (this.x + this.width > canvas.width) this.x = canvas.width - this.width;
    }
}

// 粒子类
class Particle {
    constructor(x, y, color) {
        this.x = x;
        this.y = y;
        this.color = color;
        this.radius = Math.random() * 3 + 1;
        this.speedX = (Math.random() - 0.5) * 5;
        this.speedY = (Math.random() - 0.5) * 5;
        this.life = 30; // 粒子寿命
    }

    update() {
        this.x += this.speedX;
        this.y += this.speedY;
        this.life--;
    }

    draw() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        ctx.fillStyle = this.color;
        ctx.fill();
        
        // 添加发光效果
        ctx.shadowBlur = 5;
        ctx.shadowColor = this.color;
        ctx.stroke();
        ctx.shadowBlur = 0;
    }
}

// 初始化游戏
function initGame() {
    // 获取Canvas元素和上下文
    canvas = document.getElementById('game-canvas');
    ctx = canvas.getContext('2d');
    
    // 设置Canvas大小为容器大小
    resizeCanvas();
    
    // 创建接球板
    paddle = new Paddle(canvas.width / 2 - 75, canvas.height - 30, 150, 15);
    
    // 初始化音效
    backgroundMusic = backgroundMusicElement;
    hitSound = hitSoundElement;
    missSound = missSoundElement;
    
    // 加载最高分
    loadHighScore();
    
    // 加载排行榜
    loadLeaderboard();
}

// 调整Canvas大小
function resizeCanvas() {
    canvas.width = canvas.clientWidth;
    canvas.height = canvas.clientHeight;
}

// 开始游戏
function startGame() {
    mainMenu.style.display = 'none';
    gameArea.style.display = 'block';
    settingsMenu.style.display = 'none';
    leaderboardMenu.style.display = 'none';
    gameOverScreen.style.display = 'none';
    
    // 重置游戏状态
    score = 0;
    level = 1;
    timeLeft = 60;
    fruits = [];
    particles = [];
    gameRunning = true;
    
    // 更新显示
    scoreElement.textContent = score;
    levelElement.textContent = level;
    timerElement.textContent = timeLeft;
    
    // 清除之前的计时器
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
    }
    
    // 重置时间相关变量
    lastTime = performance.now();
    lastFruitGenerationTime = lastTime;
    
    // 播放背景音乐
    if (musicEnabled) {
        backgroundMusic.currentTime = 0;
        backgroundMusic.play().catch(e => console.log('无法自动播放音乐:', e));
    }
    
    // 开始游戏循环
    requestAnimationFrame(gameLoop);
    
    // 开始新的计时器
    startTimer();
}

// 游戏主循环
function gameLoop(timestamp) {
    if (!gameRunning) return;
    
    // 计算时间差
    const deltaTime = timestamp - lastTime;
    lastTime = timestamp;
    
    // 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 生成新水果
    if (timestamp - lastFruitGenerationTime > fruitGenerationInterval) {
        generateFruit();
        lastFruitGenerationTime = timestamp;
        
        // 随着等级提高，减少生成间隔
        fruitGenerationInterval = Math.max(500, 1500 - level * 100);
    }
    
    // 更新和绘制所有水果
    updateFruits();
    
    // 更新和绘制粒子
    updateParticles();
    
    // 绘制接球板
    paddle.draw();
    
    // 继续游戏循环
    if (gameRunning) {
    requestAnimationFrame(gameLoop);
    }
}

// 开始倒计时
function startTimer() {
    // 确保清除之前的计时器
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
    }
    
    timerInterval = setInterval(() => {
        if (!gameRunning) {
            clearInterval(timerInterval);
            return;
        }
        
        timeLeft--;
        timerElement.textContent = timeLeft;
        
        if (timeLeft <= 0) {
            endGame('timeout');
        }
    }, 1000);
}

// 生成新水果
function generateFruit() {
    const radius = Math.random() * 10 + 10; // 半径在10-20之间
    const x = Math.random() * (canvas.width - 2 * radius) + radius;
    const y = 0 - radius; // 从画布顶部外开始
    
    // 根据等级决定水果类型概率
    const typeRand = Math.random();
    let type = 'normal';
    let points = 1;
    let color;
    let name;
    
    // 水果类型和颜色
    const fruitTypes = [
        { type: 'normal', color: '#ff6b6b', points: 1, name: '苹果' },     // 苹果
        { type: 'normal', color: '#ffa502', points: 1, name: '橙子' },     // 橙子
        { type: 'normal', color: '#2ed573', points: 1, name: '香蕉' },     // 香蕉
        { type: 'normal', color: '#1e90ff', points: 1, name: '蓝莓' },     // 蓝莓
        { type: 'special', color: '#ff4757', points: 3, name: '草莓' },     // 特殊水果
        { type: 'bomb', color: '#ff0000', points: -10, name: '炸弹' }      // 炸弹水果
    ];
    
    // 根据等级增加特殊水果的概率
    if (typeRand < 0.1 * level) { // 10%概率生成特殊水果
        const specialFruit = fruitTypes.find(f => f.type === 'special');
        type = specialFruit.type;
        points = specialFruit.points;
        color = specialFruit.color;
        name = specialFruit.name;
    } else if (typeRand < 0.2 * level) { // 10%概率生成炸弹水果
        const bombFruit = fruitTypes.find(f => f.type === 'bomb');
        type = bombFruit.type;
        points = bombFruit.points;
        color = bombFruit.color;
        name = bombFruit.name;
    } else {
        // 随机选择普通水果
        const normalFruits = fruitTypes.filter(f => f.type === 'normal');
        const randomFruit = normalFruits[Math.floor(Math.random() * normalFruits.length)];
        type = randomFruit.type;
        points = randomFruit.points;
        color = randomFruit.color;
        name = randomFruit.name;
    }
    
    // 随机速度
    const speedX = (Math.random() - 0.5) * 4;
    const speedY = Math.random() * 2 + 1;
    
    // 创建水果
    const fruit = new Fruit(x, y, radius, speedX, speedY, color, points, type, name);
    fruits.push(fruit);
}

// 更新所有水果
function updateFruits() {
    for (let i = fruits.length - 1; i >= 0; i--) {
        const fruit = fruits[i];
        
        // 更新位置
        fruit.update();
        
        // 检查碰撞
        const collisionType = fruit.checkCollision(paddle);
        
        if (collisionType === 'bomb') {
            // 炸弹水果爆炸，结束游戏
            createExplosion(fruit.x, fruit.y, fruit.color);
            endGame('bomb');
            return;
        } else if (collisionType === 'special') {
            // 特殊水果增加更多分数
            score += fruit.points * 2; // 特殊水果双倍分数
            createExplosion(fruit.x, fruit.y, fruit.color);
            fruits.splice(i, 1);
            if (soundEnabled) {
                hitSound.play().catch(e => console.log('无法播放音效:', e));
            }
        } else if (collisionType === 'normal') {
            // 普通水果正常加分
            score += fruit.points;
            createExplosion(fruit.x, fruit.y, fruit.color);
            fruits.splice(i, 1);
            if (soundEnabled) {
                hitSound.play().catch(e => console.log('无法播放音效:', e));
            }
        }
        
        // 如果水果掉出画布底部
        if (fruit.y - fruit.radius > canvas.height) {
            // 如果不是炸弹水果，扣分
            if (fruit.type !== 'bomb') {
                score = Math.max(0, score - 1); // 不让分数变成负数
                if (soundEnabled) {
                    missSound.play().catch(e => console.log('无法播放音效:', e));
                }
            }
            fruits.splice(i, 1);
            continue;
        }
        
        // 绘制水果
        fruit.draw();
    }
    
    // 更新分数显示
    scoreElement.textContent = score;
}

// 创建爆炸效果
function createExplosion(x, y, color) {
    for (let i = 0; i < 20; i++) {
        particles.push(new Particle(x, y, color));
    }
}

// 更新粒子
function updateParticles() {
    for (let i = particles.length - 1; i >= 0; i--) {
        const particle = particles[i];
        
        // 更新位置
        particle.update();
        
        // 绘制粒子
        particle.draw();
        
        // 移除寿命结束的粒子
        if (particle.life <= 0) {
            particles.splice(i, 1);
        }
    }
}

// 结束游戏
function endGame(reason = 'timeout') {
    // 防止重复调用
    if (!gameRunning) return;
    
    gameRunning = false;
    
    // 清除计时器
    if (timerInterval) {
    clearInterval(timerInterval);
        timerInterval = null;
    }
    
    // 显示游戏结束界面
    gameOverScreen.style.display = 'block';
    
    // 更新最终分数
    finalScoreElement.textContent = score;
    
    // 设置结束原因提示
    const gameOverTitle = document.querySelector('#game-over h2');
    if (gameOverTitle) {
        if (reason === 'bomb') {
            gameOverTitle.textContent = '💥 碰到炸弹，游戏结束！';
            gameOverTitle.style.color = '#ff4444';
        } else {
            gameOverTitle.textContent = '游戏结束！';
            gameOverTitle.style.color = '#00e5ff';
        }
    }
    
    // 更新并保存最高分
    const highScore = localStorage.getItem('highScore') || 0;
    if (score > highScore) {
        localStorage.setItem('highScore', score);
        highScoreElement.textContent = score;
    } else {
        highScoreElement.textContent = highScore;
    }
    
    // 清空水果
    fruits = [];
    
    // 停止背景音乐
    if (musicEnabled) {
        backgroundMusic.pause();
    }
}

// 重新开始游戏
function restartGame() {
    // 隐藏游戏结束界面
    gameOverScreen.style.display = 'none';
    
    // 重置游戏状态
    score = 0;
    level = 1;
    timeLeft = 60;
    fruits = [];
    particles = [];
    gameRunning = true;
    
    // 更新显示
    scoreElement.textContent = score;
    levelElement.textContent = level;
    timerElement.textContent = timeLeft;
    
    // 清除之前的计时器
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
    }
    
    // 重置时间相关变量
    lastTime = performance.now();
    lastFruitGenerationTime = lastTime;
    
    // 播放背景音乐
    if (musicEnabled) {
        backgroundMusic.currentTime = 0;
        backgroundMusic.play().catch(e => console.log('无法播放音乐:', e));
    }
    
    // 开始游戏循环
    requestAnimationFrame(gameLoop);
    
    // 开始新的计时器
    startTimer();
}

// 设置重新开始按钮的事件监听器
function setupRestartButton() {
    const restartButton = document.getElementById('restart-button');
    if (restartButton) {
        restartButton.addEventListener('click', restartGame);
    }
}

// 在初始化时设置重新开始按钮
document.addEventListener('DOMContentLoaded', () => {
    setupRestartButton();
});

// 监听开始按钮点击
startButton.addEventListener('click', () => {
    startGame();
});

// 监听退出按钮点击
document.getElementById('exit-button')?.addEventListener('click', () => {
    if (gameRunning) {
        endGame('timeout');
    }
});

// 设置音效开关
document.getElementById('sound-toggle').addEventListener('change', (e) => {
    soundEnabled = e.target.checked;
});

document.getElementById('music-toggle').addEventListener('change', (e) => {
    musicEnabled = e.target.checked;
    if (musicEnabled) {
        backgroundMusic.play().catch(e => console.log('无法播放音乐:', e));
    } else {
        backgroundMusic.pause();
    }
});

// 监听鼠标移动
gameArea.addEventListener('mousemove', (e) => {
    if (!gameRunning) return;
    
    // 获取鼠标相对于游戏区域的位置
    const rect = gameArea.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    
    // 更新接球板位置
    paddle.update(mouseX);
});

// 加载最高分
function loadHighScore() {
    const highScore = localStorage.getItem('highScore') || 0;
    highScoreElement.textContent = highScore;
}

// 加载排行榜
function loadLeaderboard() {
    // 这里可以添加从服务器加载排行榜数据的代码
    // 暂时使用本地存储的最高分
    const highScore = localStorage.getItem('highScore') || 0;
    const leaderboardBody = document.getElementById('leaderboard-body');
    if (leaderboardBody) {
        leaderboardBody.innerHTML = `
            <tr>
                <td>1</td>
                <td>玩家</td>
                <td>${highScore}</td>
            </tr>
        `;
    }
}

// 初始化游戏
initGame();